package com.jinxin.platform.cdacscontrolmgr.utils;

import com.alibaba.fastjson.JSONObject;
import com.jinxin.platform.cdacscontrolmgr.common.Constant;
import org.apache.commons.codec.binary.Base64;
import org.springframework.util.StringUtils;

import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * All rights Reserved, Designed By www.beonelot.com
 *
 * @version: V1.0
 * @Copyright: www.beonelot.com Inc. All rights reserved.
 * @Description：
 * @Date: 2021-02-24
 * @Author: Lingnan
 **/
public class StringUtil {

    public static String base64ForHexStr(String cmd){
        if(StringUtils.isEmpty(cmd)){return "";}
        byte[] bytes = NumConvertUtil.hexStringToByteArray(cmd.replace(" ",""));
        return getBase64String(bytes);
    }

    public static String convertStr2Hex(String msg){
        //先把字符串按gb2312转成byte数组
        byte[] bytes = new byte[0];
        try {
            bytes = msg.getBytes(Constant.CHARSET_GB2312);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return "";
        }
        StringBuilder gbString = new StringBuilder();
        for (byte b : bytes){
            // 再用Integer中的方法，把每个byte转换成16进制输出
            String temp = Integer.toHexString(b);
            //判断进行截取
            if(temp.length()>=8){
                temp = temp.substring(6, 8);
            }
            gbString.append(temp);
        }
        return gbString.toString().toUpperCase();
    }

    public static int getBytesLength(String msg){
        byte[] bytes = new byte[0];
        try {
            bytes = msg.getBytes(Constant.CHARSET_GB2312);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return bytes.length;
    }

    public static String getBase64String(byte[] bytes) {
        byte[] base64_data = java.util.Base64.getEncoder().encode(bytes);
        return new String(base64_data);
    }

    public static String getCarNum(String s){
        String s1 = decodeBase64(s, Charset.forName(Constant.CHARSET_GBK));
        String[] split = s1.split(Constant.REGEX_JSON_RIGHT);
        String carNumJson = split[0]+Constant.REGEX_JSON_RIGHT;
        JSONObject returnJson = JSONObject.parseObject(carNumJson);
        JSONObject plateResult = returnJson.getJSONObject("PlateResult");
        return plateResult.getString("license");
    }

    public static String encodeBase64(String base64Str){
        return new String(Base64.encodeBase64(base64Str.getBytes()), StandardCharsets.UTF_8);
    }

    public static String decodeBase64(String base64Str, Charset charset) {
        return new String(Base64.decodeBase64(base64Str.getBytes()), charset);
    }

    public static String getUuid() {
        UUID uuid = UUID.randomUUID();
        return uuid.toString().replace("-", "");
    }

    public static boolean isEmpty(String str){
        if(StringUtils.isEmpty(str)){return true;}
        String s = str.trim();
        return s.length() == 0;
    }

    public static String stringToGbk(String str){
        if(StringUtils.isEmpty(str)){return "";}
        byte[] bytes = new byte[str.length()/2];
        for (int i = 0; i < bytes.length; i++) {
            byte high = Byte.parseByte(str.substring(i*2,i*2+1),16);
            byte low = Byte.parseByte(str.substring(i*2+1,i*2+2),16);
            bytes[i] = (byte) (high << 4 | low);
        }
        try {
            return new String(bytes,"gbk");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "";
    }

    //将byte数组转成16进制字符串
    public static String bytesToHexFun(byte[] bytes) {
        char[] HEX_CHAR = {'0', '1', '2', '3', '4', '5',
                '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
        // 一个byte为8位，可用两个十六进制位标识
        char[] buf = new char[bytes.length * 2];
        int a = 0;
        int index = 0;
        for(byte b : bytes) { // 使用除与取余进行转换
            if(b < 0) {
                a = 256 + b;
            } else {
                a = b;
            }
            buf[index++] = HEX_CHAR[a / 16];
            buf[index++] = HEX_CHAR[a % 16];
        }
        return new String(buf);
    }

    public static String chineseToGB2312(String chinese,int byteLength){
        // 先把字符串按gb2312转成byte数组
        byte[] bytes = new byte[0];
        try {
            bytes = chinese.getBytes("gb2312");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        StringBuilder gbString = new StringBuilder();
        List<String> stringList = new ArrayList<>();
        // 遍历数组
        for (byte b : bytes){
            // 再用Integer中的方法，把每个byte转换成16进制输出
            String temp = Integer.toHexString(b).toUpperCase();
            // 截取
            temp = temp.substring(6, 8);
            stringList.add(temp);
            gbString.append(" ").append(temp);
        }
        int hexLen = stringList.size();
        int len = byteLength > hexLen ? byteLength-hexLen : 0;
        for(int i=0;i<len;i++){
            stringList.add(Constant.KEEP_VALUE);
        }
        return stringList.stream().map(String::valueOf).collect(Collectors.joining(" "));
    }


    public static void main(String[] args) throws UnsupportedEncodingException {
        System.out.println(chineseToGB2312("密码错误",9));
        String str = "aaaa_%BA%DAAF6655.jpg";
        String jpgName = str.substring(str.lastIndexOf("_%") + 2).replaceAll("%", "");
        System.out.println(jpgName.substring(0,4));
        System.out.println(jpgName.substring(4));
//        System.out.println(stringToGbk("B4A8"));
//        String[] strings = new String[]{"川","粤","京","闽","浙","沪","鄂","湘","赣","琼","津","渝","冀","豫","皖","桂","黔","晋",
//                "辽","吉","黑","苏","鲁","云","陕","甘","青","台","蒙","宁","新","藏","港","澳"};
//        for (int i = 0; i < strings.length; i++) {
//            try {
//                System.out.println(bytesToHexFun(strings[i].getBytes("GB2312")));
//            } catch (UnsupportedEncodingException e) {
//                e.printStackTrace();
//            }
//        }
    }
}
